package com.xuxueli.applyModules.service;
import com.alibaba.fastjson.JSONObject;
import com.xuxueli.applyModules.entity.TmpFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class BatchSearchService {

    public void downloadServiceTemplate(Long serviceId, OutputStream out) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        Row row = sheet.createRow(0);
        List<Map<String,String>> requestParams = new ArrayList<>();
        Map map = new HashMap();
        map.put("code","");
        map.put("name","");
        map.put("serviceId",serviceId);
        requestParams.add(map);
        if (requestParams != null && !requestParams.isEmpty()) {
            Cell cell;
            for (int index = 0; index < requestParams.size(); index++) {
                cell = row.createCell(index);
                cell.setCellType(CellType.STRING);
                cell.setCellValue(requestParams.get(index).get("code"));
            }
        }
        try {
            workbook.write(out);
            out.flush();
        } catch (IOException e) {
            log.error("下载模板失败", e);
        }
    }

    public Map<String, Object> handleRequestParam(String body, HttpServletRequest request) {
        if (StringUtils.isNotEmpty(body)) {
            return JSONObject.parseObject(body);
        }
        Map<String, Object> parameters = new ConcurrentHashMap<>(16);
        try {
            request.getParts().forEach(part -> {
                byte[] content;
                try (InputStream in = part.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                    byte[] bytes = new byte[2048];
                    int length;
                    while ((length = in.read(bytes)) != -1) {
                        out.write(bytes, 0, length);
                    }
                    content = out.toByteArray();
                    if (part.getSubmittedFileName() != null) {
                        parameters.put(part.getName(),
                                JSONObject.toJSONString(new TmpFile(part.getSubmittedFileName(), content)));
                    } else {
                        parameters.put(part.getName(), new String(content, StandardCharsets.UTF_8));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            });
        } catch (IOException | ServletException e) {
            log.error("获取Part参数失败");
        }
        return parameters;
    }

//    private void setBody(){
//        TestResultBO testResultBO = new TestResultBO();
//        Response feignResponse = Response.builder().build();
//        try (InputStream in = feignResponse.body().asInputStream()) {
////            if (returnStream) {
////                ResponseUtil.responseWrite(in, response);
////            }
//            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
//            byte[] bytes = new byte[2048];
//            int length;
//            while ((length = in.read(bytes)) != -1) {
//                byteOut.write(bytes, 0, length);
//            }
//            testResultBO = JSONObject
//                    .parseObject(new String(byteOut.toByteArray(), StandardCharsets.UTF_8), TestResultBO.class);
//        } catch (Exception e) {
//            testResultBO = new TestResultBO();
//        }
//        System.out.println(testResultBO);
//    }


    public void downloadSql(HttpServletResponse response) {
        try {
            String fileName = "test" + ".sql";
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/plain;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            StringBuilder createSql = new StringBuilder();
            createSql.append("alter table test_role rename test_roles");
            try (OutputStream out = response.getOutputStream()) {
                out.write(createSql.toString().getBytes(StandardCharsets.UTF_8));
                out.flush();
            }
            response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
